package com.guinea.skosite.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.guinea.account.entity.Attach;
import com.guinea.account.service.AttachManager;
import com.guinea.core.Constants;
import com.guinea.core.orm.BaseEntity;
import com.guinea.core.utils.CommonUtils;
import com.guinea.core.utils.StringUtils;
import com.guinea.core.web.StrutsAction;
import com.guinea.skoru.entity.SkoruImage;
import com.guinea.skoru.service.SkoruImageManager;
import com.guinea.skosite.form.SkoruImageForm;

public class SkositeImageAction extends StrutsAction {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	AttachManager attachManager;

	SkoruImageManager skoruImageManager;

	public AttachManager getAttachManager() {
		return attachManager;
	}

	public void setAttachManager(AttachManager attachManager) {
		this.attachManager = attachManager;
	}

	public SkoruImageManager getSkoruImageManager() {
		return skoruImageManager;
	}

	public void setSkoruImageManager(SkoruImageManager imageManager) {
		this.skoruImageManager = imageManager;
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		SkoruImageForm imageForm = (SkoruImageForm) form;
		//save操作前的验证
		String errorText = validateImageForm(imageForm,mapping, form, request, response);
		if(!StringUtils.isBlank(errorText)){
			renderHtml(response, "<script>parent.showError('" + errorText
					+  "')</script>");
			return null;
		} 
		SkoruImage image = new SkoruImage();
		// 保存附件
		String webPathRoot = "/attachments";
		FormFile f = imageForm.getFile();
		Attach attach = new Attach();
		attach.setStatus(Constants.STATUS_VALID);
		attach.setCreated(new Date());
		attach.setCreator(CommonUtils.getCurrentUserId());
		attach.setFileName(f.getFileName());
		attach.setFileSize(new Long(f.getFileSize()));
		attach.setWebPath(webPathRoot);
		getAttachManager().save(attach);

		String physicalPath = System.getProperty("app.phy_path")
				+ attach.getWebPath();
		String fileType = "";
		int dotIndex = f.getFileName().lastIndexOf(".");
		if (dotIndex > -1) {
			fileType = "." + f.getFileName().substring(dotIndex + 1);
		}
		attach.setWebPath(webPathRoot + "/" + attach.getId().longValue()
				+ fileType);
		getAttachManager().save(attach);

		InputStream in = null;
		FileOutputStream out = null;
		try {
			in = f.getInputStream();
			File dir = new File(physicalPath);
			if (!dir.exists())
				dir.mkdirs();
			out = new FileOutputStream(physicalPath + "/"
					+ attach.getId().longValue() + fileType);
			CommonUtils.io(in, out);
		} catch (FileNotFoundException e) {
			logger.error("write attach id " + attach.getId() + " :", e);
		} catch (IOException e) {
			logger.error("write attach id " + attach.getId() + " :", e);
		}
		// 保存图片信息
		image.setStatus(Constants.STATUS_VALID);
		image.setCreated(new Date());
		image.setCreator(CommonUtils.getCurrentUserId());
		image.setRegionId(imageForm.getRegionId());
		image.setAttachId(attach.getId());
		image.setTypeCode(imageForm.getTypeCode());
		getSkoruImageManager().save(image);

		renderHtml(response, "<script>parent.showImage('" + image.getTypeCode()
				+ "','" + attach.getWebPath() + "',"
				+ attach.getId().longValue() + ")</script>");
		return null;
	}

	/**
	 * 删除
	 */
	public ActionForward erase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String idString = request.getParameter("id");
		Long id = null;
		if (!StringUtils.isBlank(idString)) {
			id = new Long(idString);
		}
		SkoruImage skoruImage = null;
		// 如果缺少ID，则返回操作失败消息
		if (id != null) {
			skoruImage = getSkoruImageManager().getSkoruImage(id);
		} else {
			renderText(response, "操作失败：未提供有效参数");
			return null;
		}
		// erase操作前的验证
		if (skoruImage == null) {
			renderText(response, "所编辑条目不存在");
			return null;
		}
		// 为保存操作添加创建人更新人等信息
		BaseEntity baseEntity = addSaveData(skoruImage, false);
		baseEntity.setStatus(Constants.STATUS_INVALID);
		getSkoruImageManager().save(baseEntity);
		//===================================
		// 删除附件信息
		Long attachId = skoruImage.getAttachId();
		Attach attach = null;
		// 如果缺少ID，则返回操作失败消息
		if (attachId != null) {
			attach = getAttachManager().getAttach(attachId);
		} else {
			renderText(response, "操作失败：未提供有效参数");
			return null;
		}
		// erase操作前的验证
		if (attach == null) {
			renderText(response, "所编辑条目不存在");
			return null;
		}
		// 为保存操作添加创建人更新人等信息
		baseEntity = addSaveData(attach, false);
		baseEntity.setStatus(Constants.STATUS_INVALID);
		getAttachManager().save(baseEntity);

		//===================================
		//删除文件
		String physicalPath = System.getProperty("app.phy_path")
				+ attach.getWebPath();
		File f = new File(physicalPath);
		f.delete();

		renderText(response, "ok");
		return null;
	}
	/**
	 * 取得SkoruShareholder对象列表
	 */
	public ActionForward getImages(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String regionId = request.getParameter("regionId");
		String result = "[";
		if(!StringUtils.isBlank(regionId)){
			List list = getSkoruImageManager().findImages(new Long(regionId));
			for (Iterator iter = list.iterator(); iter.hasNext();) {
				SkoruImage f = (SkoruImage) iter.next();
				result += "{";
				result += "\"id\" : \"" + (f.getId() == null? "":f.getId().longValue()+"") + "\"";
				result += ", \"regionId\" : \"" + (f.getRegionId() == null? "":f.getRegionId().longValue()+"") + "\"";
				result += ", \"typeCode\" : \"" + StringUtils.defaultString(f.getTypeCode()) + "\"";
				result += ", \"attachId\" : \"" + (f.getAttachId() == null? "":f.getAttachId().longValue()+"") + "\"";
				Attach attach = getAttachManager().getAttach(f.getAttachId());
				result += ", \"attachPath\" : \"" + StringUtils.defaultString(attach.getWebPath()) + "\"";
				result += "}";
				if(iter.hasNext()) result += ", ";
			}
		}
		result += "]";
		renderText(response,result);
		return null;
	}
	/**
	 * save操作前的验证
	 * @param object
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	protected String validateImageForm(SkoruImageForm imageForm,ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		if(imageForm == null) return "提交信息为空。";
		if(imageForm.getRegionId() == null || imageForm.getTypeCode() == null) 
			return "缺少必要参数。";
		//上传文件大小
		FormFile f = imageForm.getFile();
		if(f == null || f.getFileSize()<1 ||f.getFileSize()> 2 * 1024 * 1024){
			 return "请上传一个大小不超过2M的图片。";
		}else{
			long totalSize = getAttachManager().getTotalSize();
			if(totalSize + f.getFileSize() > 20 * 1024 * 1024){
				return "您上传的图片总大小已超过20M，您可以通过删除历史草稿中的图片来释放空间。";
			}
		}
		return null;
	}
	
}
